<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :before-close="handleCancel"
      :close-on-click-modal="false"
      center
      width="40%"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="rules" size="small">
        <el-form-item label="角色ID" :label-width="labelWidth" prop="pkId" v-if="!isAdd" hidden="hidden">
          <el-input v-model="editForm.pkId" placeholder="请输入权限ID"></el-input>
        </el-form-item>
        <el-form-item label="权限类型" :label-width="labelWidth" prop="menuType">
          <el-radio-group v-model="menuType" @change="onChangeMenuType">
            <el-radio :label="0">一级菜单</el-radio>
            <el-radio :label="1">子菜单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限标识" :label-width="labelWidth" prop="code">
          <el-input v-model="editForm.code" placeholder="请输入权限标识"></el-input>
        </el-form-item>
        <el-form-item
          label="上级权限"
          :label-width="labelWidth"
          prop="upermissionName"
          v-show="menuType !== 0"
          ref="upermissionForm"
        >
          <el-input
            v-model="editForm.upermissionName"
            ref="upermissionInput"
            placeholder="请选择上级权限"
            @focus="deptFocus"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="上级权限Id"
          :label-width="labelWidth"
          prop="upermissionId"
          v-show="menuType !== 0"
          hidden="hidden"
        >
          <el-input v-model="editForm.upermissionId" placeholder="请选择上级权限" @focus="deptFocus"></el-input>
        </el-form-item>
        <el-form-item label="前端组件" :label-width="labelWidth" prop="frontPath">
          <el-input placeholder="请输入前端组件" v-model="editForm.frontPath"></el-input>
        </el-form-item>
        <el-form-item label="权限名称" :label-width="labelWidth" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入权限名称"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" :label-width="labelWidth" prop="isEnable">
          <el-radio v-model="editForm.isEnable" label="0">否</el-radio>
          <el-radio v-model="editForm.isEnable" label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="权限url" :label-width="labelWidth" prop="url">
          <el-input v-model="editForm.url" placeholder="请输入权限url"></el-input>
        </el-form-item>
        <el-form-item label="默认跳转地址" :label-width="labelWidth" prop="thdUrl" v-show="menuType === 0">
          <el-input v-model="editForm.thdUrl" placeholder="请输入默认跳转地址"></el-input>
        </el-form-item>
        <el-form-item label="菜单图标" :label-width="labelWidth" prop="menuIcon">
          <el-input v-model="editForm.menuIcon" placeholder="请输入菜单图标"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="labelWidth" prop="orderIndex">
          <el-input v-model="editForm.orderIndex" placeholder="请输入排序"></el-input>
        </el-form-item>

        <el-form-item label="备注" :label-width="labelWidth" prop="remark">
          <el-input type="textarea" v-model="editForm.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="hanldeSave('editFormRef')" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <upermission-tree-modal
      ref="UpermissionTreeModal"
      :checkUpermissionInfo="checkUpermissionInfo"
      @deptModalOk="deptModalOk"
    ></upermission-tree-modal>
  </div>
</template>

<script>
import { getJurisdictionTreeList, addJurisdiction, editJurisdiction } from '../js/auth'
import UpermissionTreeModal from './UpermissionTreeModal'
import pick from 'lodash.pick'
export default {
  name: 'UpermissionModal',
  data () {
    return {
      title: '权限新增',
      isAdd: false,
      dialogVisible: false, // 编辑弹窗
      labelWidth: '100px',
      editForm: {
        pkId: '',
        upermissionName: '',
        name: '',
        pid: '',
        code: '',
        isEnable: '',
        url: '',
        remark: '',
        orderIndex: ''
      },
      model: {},
      rules: {
        pkId: [{ required: true, message: '请输入权限ID', trigger: 'blur' }],
        upermissionId: [{ required: true, message: '请选择上级权限Id', trigger: 'blur' }],
        upermissionName: [{ required: true, message: '请选择上级权限', trigger: 'blur' }],
        frontPath: [{ required: false, message: '请输入前端组件', trigger: 'blur' }],
        menuType: [{ required: false, message: '', trigger: 'blur' }],
        code: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
        name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
        isEnable: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
        url: [{ required: true, message: '请输入权限URL', trigger: 'blur' }],
        menuIcon: [{ required: false, message: '请输入菜单图标', trigger: 'blur' }],
        thdUrl: [{ required: false, message: '请输入默认跳转地址', trigger: 'blur' }],
        orderIndex: [{ required: false, message: '请输入排序', trigger: 'blur' }],
        remark: [{ required: false, message: '请输入权限备注', trigger: 'blur' }]
      },
      menuPid: 0,
      menuType: 0,
      checkUpermissionInfo: {},
      UpermissionData: [],
      ParentNodeData: {}
    }
  },
  components: { UpermissionTreeModal },
  computed: {},
  methods: {
    // 新增
    add () {
      this.edit({ pid: 0, parentId: 0 })
    },
    // 编辑
    edit (record) {
      this.dialogVisible = true
      this.model = Object.assign({}, record)
      this.$nextTick(() => {
        this.$refs.editFormRef.resetFields()
        if (!this.isAdd) {
          this.editForm = pick(
            this.model,
            'pkId',
            'code',
            'name',
            'frontPath',
            'isEnable',
            'url',
            'menuIcon',
            'orderIndex',
            'remark'
          )
          if (this.model.pid === 0) {
            this.editForm = Object.assign({}, this.editForm, {
              upermissionName: '父节点',
              upermissionId: 0
            })
            this.checkUpermissionInfo = {
              id: 0
            }
            this.menuType = 0
            this.show = false
          } else {
            this.menuType = 1
            this.show = true
            this.getUpermissionTreeTree()
          }
        } else {
          this.editForm = Object.assign({}, this.editForm, {
            upermissionName: '父节点',
            upermissionId: 0
          })
          this.checkUpermissionInfo = {
            id: 0
          }
        }
      })
    },
    // 查询tree
    async getUpermissionTreeTree () {
      let params = {}
      let res = await getJurisdictionTreeList(params)
      if (res.code === 0 && res.data) {
        this.options = []
        this.UpermissionData = res.data
        this.ParentNodeData = await this.familyTree(this.UpermissionData, this.model.parentId)
        this.$nextTick(() => {
          const { parentId, pkId, name } = this.ParentNodeData
          this.editForm = Object.assign({}, this.editForm, {
            upermissionName: name,
            upermissionId: parentId
          })
          this.checkUpermissionInfo = {
            id: pkId
          }
        })
      } else {
        this.$message.warning(res.msg)
      }
    },
    async familyTree (data, id) {
      var temp = {}
      var forFn = function (data, id) {
        for (var i = 0; i < data.length; i++) {
          var item = data[i]
          if (item.pkId === id) {
            temp = item
            forFn(data, item.parentId)
            break
          } else {
            if (item.children) {
              forFn(item.children, id)
            }
          }
        }
      }
      forFn(data, id)
      return temp
    },
    handleCancel () {
      this.dialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    onChangeMenuType (value) {
      this.menuType = value
      if (value === 1) {
        this.show = false
        this.editForm = Object.assign({}, this.editForm, { upermissionName: '', upermissionId: '' })
        this.checkUpermissionInfo = {}
      } else {
        this.show = true
        this.editForm = Object.assign({}, this.editForm, {
          upermissionName: '父节点',
          upermissionId: 0
        })
        this.checkUpermissionInfo = {
          id: 0
        }
      }
    },
    hanldeSave (editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          let res, msg
          const values = {
            ...this.editForm
          }
          if (this.isAdd) {
            res = await addJurisdiction(Object.assign({}, values, { pid: this.checkUpermissionInfo.id }))
            msg = '保存成功！'
          } else {
            res = await editJurisdiction(
              Object.assign({}, values, {
                permissionId: this.editForm.pkId,
                pid: this.checkUpermissionInfo.id
              })
            )
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          this.handleCancel()
        }
      })
    },
    // 回调
    deptModalOk (val) {
      this.checkUpermissionInfo = val
      this.editForm = Object.assign({}, this.editForm, {
        upermissionName: val.label,
        upermissionId: val.id
      })
      this.checkUpermissionInfo = {
        id: val.id
      }
      this.$refs['upermissionForm'].clearValidate()
    },
    // 输入框获取焦点并手动失去焦点
    deptFocus () {
      this.$refs.UpermissionTreeModal.add()
      this.$refs.upermissionInput.blur()
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
.el-dialog {
  .el-input,
  .el-select {
    width: 100%;
  }
}
/deep/ .el-dialog__body {
  padding-bottom: 0;
}
</style>
